<template>
	<view class="cu-card bg-white" style="height: 100%;">
		<action-bar backTitle="返回首页" title="账单列表"></action-bar>
		<!-- 消费统计 -->
		<view>
			<view class="padding flex justify-around">
				<picker fields="month" mode="date" :end="display.dateEndRange" @change="dateTimeSwitcher">
					<button class="cu-btn round line-blue">#<text v-text="display.date"></text></button>
				</picker>
				
				<button class="cu-btn bg-blue text-price round amount" @click="turn_to_income_page()">收入#<text class="text-bold" v-text="display.income"></text></button>
				<button class="cu-btn bg-red text-price round amount" @click="turn_to_expenditure_page()">支出#<text class="text-bold" v-text="display.outcome"></text></button>
			</view>
			<view class="flex justify-around">
				<button class="cu-btn round line-blue" @click="turn_to_bill_page()">#账单</button>
				<button class="cu-btn round line-blue" @click="turn_to_budget_page()">#预算</button>
				<button class="cu-btn round line-blue" @click="turn_to_summary_page()">#统计</button>
				<button class="cu-btn round line-blue" @click="turn_to_rank_page()">#排行</button>
				<button class="cu-btn round line-blue" @click="turn_to_more_page()">#更多</button>
			</view>
		</view>
		
		<!-- 具体消费列表 -->
		<view class="cu-chat margin-top" style="min-height: 68vh;">
			<view v-if="true" class="cu-item" v-for="(item, index) in recordContent" :key="index" :class="item.userId == user_id ? 'self' : ''">
				<view class="text-gray nickname" v-text="item.nickname || 'N/A'"></view>
				<!-- 他人头像区 -->
				<view v-if="item.userId != user_id" @click="turn_to_user_page(item.userId)" class="cu-avatar radius" :style="'background-image: url(' + item.avatarUrl + ')'"></view>
				<!-- 内容区 -->
				<view class="main" @click="updateOrViewRecord(item.id, item.userId)">
					<view class="content shadow" :class="(item.secretStatus == '0' || admin) ? item.recordType == '1' ? 'bg-red' : 'bg-blue' : 'bg-brown'" style="flex-direction: column; align-items: flex-start;">
						<view>
							<text v-text="changeSecretTag(item.userId, item.styleName, item.recordType, item.secretStatus, item.recordAmount)"></text>
						</view>
						<view v-if="item.recordComment" class="word-content" style="overflow: hidden;width: 100%;">
							<text class="text-sm">备注: {{item.recordComment}}</text>
						</view>
					</view>
				</view>
				<!-- 本人头像区 -->
				<view v-if="item.userId == user_id" class="cu-avatar radius" :style="'background-image: url(' + item.avatarUrl + ')'"></view>
				<view class="date" v-text="dateFormat(item.updateDate)"></view>
			</view>
			<view v-if="!hasNextPage" class="cu-info round">加载完成</view>
		</view>
		
		
		<!-- 评论框组件 -->
		<!-- .native在组件中监听原生事件 -->
		<input-bar buttonName="开始记账" @click.native="record()" :disabled="true"></input-bar>
	</view>
</template>

<script>
	import {dateFormat, dateTransfer, concatZero} from '../../common/dateUtils.js'
	import {isAdmin} from '../../common/permission.js'
	export default {
		data() {
			return {
				admin: false,	// 管理员标识
				book_id: null,  // 当前账本ID
				book_budget: null,	 // 账本预算
				user_id: null,  	 // 当前用户ID
				bookUserId: null,	 // 当前账本用户ID
				curPage: 1,  		 // 当前页
				recordContent: [],	 // 接收到的数据
				hasNextPage: true,	 // 是否还有数据
				display: {
					date: '',		 // 展示的日期
					dateEndRange: '',// 最大允许的日期
					income: 0,		 // 收入总额
					outcome: 0,	 	 // 支出总额
					
				},
				queryCondition: {
					date: '',		 // 日期查询参数
				}
			}
		},
		
		/**
		 * 页面刚被加载时
		 * @param {Object} option
		 */
		onLoad(option) {
			this.user_id = this.$store.state.userInfo.id
			this.book_id = option.id
			this.book_budget = option.budget
			this.bookUserId = option.uid
			this.admin = this.isAdmin()
			
			// if (!this.book_budget) {
			// 	this.book_budget = uni.getStorageSync('budget')
			// }

			if (!this.book_id) {
				uni.navigateBack()
				uni.showToast({title: '账本初始化失败', icon: 'error'})
				return
			}
			
			// 初始化当前日期
			let now = new Date()
			this.display.date = `${now.getFullYear()}年${now.getMonth() + 1}月`			// 页面显示的日期格式
			this.display.dateEndRange = now.toLocaleDateString().replaceAll('/', '-')	// 日期限制，不能超过当前月份
			this.queryCondition.date = `${now.getFullYear()}${concatZero(now.getMonth() + 1)}`
		},
		
		/**
		 * 页面展示时
		 */
		onShow() {
			this.refreshQueryParams()
			this.queryByPage()			// 分页查询显示数据
			this.queryAmountByDate()	// 根据日期查询收入和支出金额
		},
		
		/**
		 * 滑动到底部时刷新
		 */
		onReachBottom() {
			if (this.hasNextPage) {
				this.queryByPage()
			}
		},
		
		onPullDownRefresh() {
			this.refreshQueryParams()
			this.queryByPage()
		},
		methods: {
			// 外部导入的函数需要满足ES6的语法
			dateFormat, dateTransfer, isAdmin,
			
			/**
			 * 查询收入 && 支出
			 */
			queryAmountByDate() {
				let queryDate = this.queryCondition.date
				if (queryDate == '') {
					let now = new Date()
					let month = now.getMonth() + 1
					queryDate = `${now.getFullYear()}${month > 9 ? month : '0' + month}`
				}
				
				this.$request({
					url: `/record/amount/${this.book_id}/${queryDate}`
				}).then(res => {
					if (res && res.data.code === 200) {
						let amounts = res.data.amount
						for (let item of amounts) {
							if (item.type == 'income') {
								this.display.income = item.amount
							} else {
								this.display.outcome = item.amount
							}
						}
					}
				})
			},
			
			/**
			 * 分页查询
			 */
			queryByPage() {
				uni.showLoading({title: '加载中'})
				this.$request({
					url: `/record/${this.book_id}/pn/${this.curPage}/le/${this.queryCondition.date}`,
					data: {
						viewAllPermission: this.$hasPermission('user:view'),
						userId: this.$store.getters.id
					}
				}).then(res => {
					if (res && res.data.code == 200) {
						this.recordContent = this.recordContent.concat(res.data.page)
						this.hasNextPage = res.data.page.length >= this.$store.state.pageSize
						this.curPage += 1
					}
				}).finally(() => {
					uni.hideLoading()
				})
			},
			
			/**
			 * picker时间选择器触发，改变选择时间
			 * 根据用户选择的时间查询记录
			 * @param {Object} e
			 */
			dateTimeSwitcher(e) {
				let date = e.detail.value
				this.queryCondition.date = date.replaceAll('-', '')
				this.display.date = `${date.substring(0, 4)}年${date.substring(5, 7)}月`
				this.refreshQueryParams()
				this.queryByPage()
			},
			
			/**
			 * 记账
			 */
			record() {
				if (this.$hasPermission('user:record')) {
					uni.navigateTo({url: `./record?book_id=${this.book_id}`})
				} else {
					this.$message.info('没有记账权限')
				}
			},
			
			
			/**
			 * 查看详细信息或者修改记录
			 * @param {Object} bookId
			 * @param {Object} recordId
			 */
			updateOrViewRecord(recordId, userId) {
				let update_url = `./record-update?bookId=${this.book_id}&recordId=${recordId}&userId=${userId}`
				uni.navigateTo({url: update_url})
			},
			
			/**
			 * 跳转到`账单`页面
			 */
			turn_to_bill_page() {
				uni.navigateTo({url: `./billing-page?bookId=${this.book_id}`})
			},
			
			/**
			 * 跳转到`排行页面`
			 */
			turn_to_rank_page() {
				uni.navigateTo({url: `./rank?bookId=${this.book_id}`})
			},
			
			/**
			 * 跳转到`更多`页面
			 */
			turn_to_more_page() {
				uni.navigateTo({url: `./more?id=${this.book_id}&uid=${this.bookUserId}`})
			},
			
			/**
			 * 跳转到`预算`页面
			 */
			turn_to_budget_page() {
				// id: 账本ID
				// budget: 预算
				// amount: 当月总支出
				uni.navigateTo({url: `./budget?id=${this.book_id}&budget=${this.book_budget}&amount=${this.display.outcome}`})
			},
			
			/**
			 * 跳转到`统计`页面
			 */
			turn_to_summary_page() {
				uni.navigateTo({url: `./summary?bookId=${this.book_id}`})
			},
			
			/**
			 * 跳转到`收入`列表
			 */
			turn_to_income_page() {
				uni.navigateTo({url: 'income-page?id=' + this.book_id})
			},
			
			/**
			 * 跳转到`支出`列表
			 */
			turn_to_expenditure_page() {
				uni.navigateTo({url: 'expenditure-page?id=' + this.book_id})
			},
		
			/**
			 * 跳转到`用户配置`页面
			 */
			turn_to_user_page(id) {
				if (id == this.bookUserId) {
					this.$message.error('没有权限')
					return;
				}
				uni.navigateTo({url: `/pages/user/update_user_permission?uid=${id}&bookId=${this.book_id}`})
			},
			
			/**
			 * 恢复刚开始加载页面时的参数数值
			 */
			refreshQueryParams() {
				this.curPage = 1
				this.hasNextPage = true
				this.recordContent = []
			},
			
			/**
			 * 记账显示内容
			 */
			changeSecretTag(userId, styleName, recordType, secretStatus, recordAmount) {
				const type = recordType == '1' ? '消费' : '收入'
				
				if (secretStatus == '0' || this.isAdmin() || userId == this.user_id) return `${styleName}-${type}-${recordAmount}元`
				// if (secretStatus == '0' || this.isAdmin() || this.$hasPermission("user:view")) return `${styleName}-${type}-${recordAmount}元`
				return '**-**-**元'
			}
		}
	}
</script>

<style>	
	page {
		padding-bottom: 100upx;
	}
	
	.word-content {
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
	
	.nickname {
		position: absolute;
		top: -15rpx;
		width: 400rpx;
		
		/* 昵称过长隐藏部分名字 */
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
	
	.amount {
		min-width: 200rpx;
	}
</style>